<?php
namespace app\controller;

use app\exception\ApiException;
use app\extensions\api\BigQuery;
use app\extensions\lib\Fcm;
use app\extensions\lib\FcmAccessToken;
use app\extensions\lib\push\BasePush;
use app\extensions\lib\push\IosPush;
use app\extensions\lib\push\Push;
use app\extensions\lib\ta_shushu\Shushu;
use app\model\Cate;
use app\model\Game;
use app\model\Package;
use app\model\TokenInfo;
use app\queue\redis\download\DownToken;
use Google\Auth\ApplicationDefaultCredentials;
use Google\Cloud\BigQuery\BigQueryClient;
use Google\Cloud\Core\ServiceBuilder;
use Google\Cloud\PubSub\PubSubClient;
use Google\Service\Bigquery\Dataset;
use Google\Service\Bigquery\QueryParameter;
use Google\Service\Bigquery\QueryParameterType;
use Google\Service\Bigquery\QueryParameterValue;
use Google\Service\Bigquery\Table;
use Google\Service\Pubsub\Topic;
use Google_Client;
use Google_Service_AnalyticsReporting;
use Google_Service_AnalyticsReporting_DateRange;
use Google_Service_AnalyticsReporting_GetReportsRequest;
use Google_Service_AnalyticsReporting_Metric;
use Google_Service_AnalyticsReporting_ReportRequest;
use Google_Service_Bigquery;
use Google_Service_Bigquery_GetIamPolicyRequest;
use Google_Service_Exception;
use Google_Service_Pubsub;
use Google_Service_Pubsub_PushConfig;
use Google_Service_Pubsub_Subscription;
use Illuminate\Support\Facades\Log;
use support\Db;
use support\Request;
use Webman\RedisQueue\Redis;

class Test
{

    public function test_callback_url(Request $request){
        Log::channel('test')->debug($request->all());
    }

    public function test(Request $request){
        Cate::getInfo(7);
        Cate::getInfo(7);
        $data = Cate::getInfo(7);
        dump('tt');
        return json_encode($data);
        $request_id = 'tapplus_admin_testtt';
        $properties = [
            'request_id' => $request_id
        ];
        $Shushu = new \app\extensions\lib\ta_shushu\Shushu(7);
        $status = $Shushu->pushLog('track_update',$request_id, '', $properties,BasePush::EVENT_SKD_REQUEST,$request_id,true);
        dump($status);
        /*$Shushu = new Shushu(7);
        $udid = 'uar_1678069919n9xkalah3y3g6xx47p';
        $properties = [
            'click_status'=> '1',
            'click_time' => '2023-03-23 07:08:54',
            'request_id' => 'tapplus_admin__641C1F69BEF196S0157189931',
            'cate_id'=>'7',
            'game_id'=>'5',
            'package_id'=>'11',
            'os_id' => '1',
            'task_id' => '162',
            'title' => '标题',
            'content' => '内容',
            'message_type' => '0',
            'result' => '{ "name": "projects/tales-of-grimm-68052822/messages/0:1679555315448160%328bcc29328bcc29" }',
            'image' => 'https://ali-tapplus-oss-01.oss-cn-guangzhou.aliyuncs.com/admin/uploads/avatar/6281fb4539d64.png',
        ];
        $message_id = '11_uar_1678069919n9xkalah3y3g6xx47p641bc5d3725ff_1679541715468_01_9172';
        $status = $Shushu->pushLog('track_update','', $udid, $properties,BasePush::EVENT_DEVICE_PUSH_LOG,$message_id,false);
        return $status;*/
        /*$data = BigQuery::getFireBaseMessaging(11,[
            'analytics_label ' => 'tapplus_push',
        ]);
        return json_encode($data);*/
        $project_id = 'tales-of-grimm-68052822';
        $appId = '1:640370011106:android:a643de7f8a8c3ba976a7bb';
        $package_id = 11;
        $package_configList = Package::getPackageConfig(1);
        $configuration = $package_configList[$package_id]['configuration'] ?? '';
        dump($configuration);
        $configuration = json_decode($configuration,true) ?: [];
        $project_id = $configuration['project_id'];
        $topic_name = 'test';
        $your_callback_url = 'https://test-push.tapplus.com/test_callback_url';
        $client = new Google_Client();
        $client->setAuthConfig($configuration);
        $client->addScope(Google_Service_Pubsub::PUBSUB);
        $tokens = ['ervd6rFhSm6h9yIH-HdPeL:APA91bHrneg__SBx68VFQbe6sorroKDL1OOAhq1AYYJ-qNaACfzgO4ziEMYFShMVkArnC9i3F990KdGzOzaLzLISJR1R2zoJtFU2mAqaxbtW9NB45RIwJSsx0oVOBz43napJ_-SQWW9C']; // 要注册的令牌列表


        $package_id = 15;
        $package_configList = Package::getPackageConfig(2);
        $configuration = $package_configList[$package_id]['configuration'] ?? '';
        $bundleID = $package_configList[$package_id]['package_name'];

        $tokens = ['992cd11c8107fca9c965366bba955081cdf95b16be8f49bbe51317845a9b6138'];
        $IosPush = new IosPush();
        $authToken = $IosPush->getPackageIdentification($package_id,0);
        return $IosPush->registerDevice('test',$bundleID,$authToken,$tokens);



        $Fcm = new Fcm();
        //$access_token = FcmAccessToken::getAccessToken($package_id,0,$configuration);
        $api_key = 'AIzaSyDxfKR8Ydx-QnRrY_u-2bm2Jq-Fjigh-NU';
        $server_key = 'AAAAlRkG6-I:APA91bHNOIBepuoJv3X_XtPBcb9FRaBduMYYGJEj4RHROkuBhqwQIR9guBjvLKPl-Zd52j4VJf5OeqoXXzdcVdgVZ8i7XJeExiFZVcdYYnBBo3j6C294tQRVQR96L5e5F0oUN6Rdt4Qf';
        $notification_key_name = 'test_688';
        $send_id = '640370011106';
        /*//return $Fcm->getDeviceGroup('640370011106',$server_key,$notification_key_name);
        $notification_key_data =  $Fcm->createDeviceGroup($send_id,$server_key,$notification_key_name,$tokens);
        $notification_key_data =  json_decode($notification_key_data,true) ?: [];
        $notification_key = $notification_key_data['notification_key'] ?? '';
        dump($notification_key);
        return $Fcm->sendDeviceGroup($send_id,$server_key,$notification_key);*/

        $topicName = 'topic_subscription_test';
        $pubsub = new PubSubClient([
            'projectId' => $project_id,
            'keyFile' => $configuration
        ]);
        $topics = $pubsub->topics();
        $ctopic = null;
        foreach ($topics as $topic) {
            $info = $topic->info();
            if($info['name']=="projects/{$project_id}/topics/{$topicName}"){
                $ctopic = $topic;
            }
        }
        !$ctopic && $ctopic = $pubsub->createTopic($topicName);

        $subscription_name = 'subscription-test';
        $subscriptions = $ctopic->subscriptions();
        $csubscription = null;
        /* @var $subscription \Google\Cloud\PubSub\Subscription */
        foreach ($subscriptions as $subscription) {
            $name = $subscription->name();
            dd($subscription->info());
            if($name=="projects/{$project_id}/subscriptions/{$subscription_name}"){
                $csubscription = $subscription;
            }
        }
        if(!$csubscription){
            $csubscription->create(); // 获取 Firebase 服务器密钥
        }



        //注册到主题
        $url = 'https://iid.googleapis.com/iid/v1:batchAdd';
        $params = [ 'to' => '/topics/' . $topicName, 'registration_tokens' => $tokens ];
        $headers = [ 'Content-Type: application/json', 'Authorization: key=' . $server_key ];
        curl($url,json_encode($params),$headers);

        $data = [
            'message' => [
                'data' => [
                    'title' => 'test_topic',
                    'body' => 'test_topic',
                ],
                'notification' => [
                    'title' => 'test_topic',
                    'body' => 'test_topic',
                ],
                'topic' => $topicName
            ]
        ];
        //推送
        $ctopic->publish([
            'data' => 'My new message.',
            'attributes' => [
                'location' => 'Detroit'
            ]
        ]);

        //拉取可用的消息
        $messages = $csubscription->pull();
        foreach ($messages as $message) {
            echo $message->data() . "\n";
            echo $message->attribute('location');
        }

        //fcm 方式推送
        $access_token = FcmAccessToken::getAccessToken($package_id,0,$configuration);
        $url = "https://fcm.googleapis.com/v1/projects/{$project_id}/messages:send";
        $header = [
            //'Connection: Keep-Alive',
            //'Keep-Alive: 300',
            'Accept:application/json',
            //'Content-Length:'.strlen(json_encode($params)),
            'Content-Type: application/json',
            'Authorization: Bearer '.$access_token,
        ];

        return curl($url,json_encode($data),1,$header);

        $pubsubService = new Google_Service_Pubsub($client);
        $topic = "projects/{$project_id}/topics/{$topic_name}";

        $credentials = ApplicationDefaultCredentials::getApplicationDefault();
        $pubsub = new PubSubClient([
            'projectId' => $project_id,
            'credentials' => $server_key,
            'keyFile'
        ]);
        /* @var $topicClass \Google\Cloud\PubSub\Topic */
        $topicClass = $pubsub->topic($topic_name);
        // 将 {project_id} 和 {topic_name} 替换为您的实际项目 ID 和主题名称
        foreach ($tokens as $token) {

            $topicClass->subscribe($token);
            /*try {
                $response = $pubsubService->projects_topics->create($topicClass,$subscription);
                dump($response);
                echo 'Token ' . $token . ' registered successfully.' . PHP_EOL;
            } catch (Google_Service_Exception $e) {
                echo 'Failed to register token ' . $token . ': ' . $e->getMessage() . PHP_EOL;
            }*/
        }

        echo 'Device tokens registered to topic successfully.' . PHP_EOL;
         /*$message = [ 'data' => [ 'title' => 'New Message', 'body' => 'Hello, this is a new message.' ] ];
        $topicClass->publish([ 'data' => $message ]);
         echo 'Message sent to topic successfully.' . PHP_EOL;*/

        //消息报告统计接口
        //$client->setSubject('sbjwwjsm@gmail.com');
        /*$client->setScopes(['https://www.googleapis.com/auth/cloud-platform','https://www.googleapis.com/auth/firebase','https://www.googleapis.com/auth/firebase.messaging']);     # 授予访问 FCM 的权限
        $service = new \Google_Service_Fcmdata($client);
        $list = $service->projects_androidApps_deliveryData
            ->listProjectsAndroidAppsDeliveryData("projects/{$project_id}/androidApps/{$appId}");
        foreach ($list as $item){
            dump($item);
        }*/

        $client->setScopes([
            Google_Service_Bigquery::BIGQUERY,
            Google_Service_Bigquery::BIGQUERY_INSERTDATA,
            Google_Service_Bigquery::CLOUD_PLATFORM,

            Google_Service_Bigquery::DEVSTORAGE_READ_ONLY,
            Google_Service_Bigquery::DEVSTORAGE_READ_WRITE,
            Google_Service_Bigquery::DEVSTORAGE_FULL_CONTROL,
            'https://www.googleapis.com/auth/bigquery',
            'https://www.googleapis.com/auth/datastore','https://www.googleapis.com/auth/cloud-platform'
        ]);
        //服务端操作类
        $service = new \Google_Service_Bigquery($client);
        $datasetId = 'firebase_messaging_test';
        //dataset 操作
        //列出dataset列表
        /*$list = $service->datasets->listDatasets($project_id);
        dump($list);*/
        //插入
        /*$postBody = [
            'datasetReference' => [
                    'datasetId' => $datasetId,
                    'projectId' => $project_id,
            ],
            'friendlyName' => 'test',
            'description' => 'test',
        ];
        $datasetId = $service->datasets->insert($project_id,new Dataset($postBody));
        dump($datasetId);*/
        //删除
        /*$datasetId = $service->datasets->delete($project_id,$datasetId);
        dump($datasetId);*/
        //获取 $datasetId信息
        /*$data = $service->datasets->get($project_id,$datasetId);
        dump($data);*/

        //更新 $datasetId信息
        /*$postBody = [
            'datasetReference' => [
                'datasetId' => $datasetId,
                'projectId' => $project_id,
            ],
            'friendlyName' => 'test6666',
            'description' => 'test6666666',
        ];
        $data = $service->datasets->update($project_id,$datasetId,new Dataset($postBody))
        $data = $service->datasets->patch($project_id,$datasetId,new Dataset($postBody)) //部分更新
        */
        //model
        //$data = $service->models->get($project_id,$datasetId,'test_m');
        //Jobs
        //$data = $service->jobs->listJobs($project_id);

        //tables
        //获取全部表
        //$data = $service->tables->listTables($project_id,$datasetId);
        //$data = $service->tables->getIamPolicy($project_id,new Google_Service_Bigquery_GetIamPolicyRequest());
        //新建表
        /*$postBody = [
            'tableReference' => [
                    'datasetId' => $datasetId,
                    'projectId' => $project_id,
                    'tableId' => 'test',
            ],
            'friendlyName' => 'test',
            'description' => 'test',
        ];*/

        //设置表结构
        /*$schema = [
            [
                'name'=>'request_id',
                'type'=>'STRING'
            ],
            [
                'name'=>'udid',
                'type'=>'STRING'
            ],
            [
                'name'=>'status',
                'type'=>'STRING'
            ],
        ];
        $table = new \Google_Service_Bigquery_Table($postBody);
        $TableSchema = new \Google_Service_Bigquery_TableSchema();
        $fields = [];
        foreach ($schema as $item){
            //字段信息
            $field = new \Google_Service_Bigquery_TableFieldSchema();
            $field->setName($item['name']);
            $field->setType($item['type']);
            $fields[] = $field;
        }
        $TableSchema->setFields($fields);//表设置全部字段array
        $table->setSchema($TableSchema);//表设置结构
        $data = $service->tables->update($project_id,$datasetId,'test',$table);*/
        //获取表信息
        //$data = $service->tables->get($project_id,$datasetId,'test');
        //删除
        //$service->tables->delete($project_id,$datasetId,'test')

        //表字段信息
        /*foreach ($data as $key =>$datum){
            $key==0 && dump($datum);
        }
        $fields = array_column($data->getSchema()->getFields(),'name');
        dump($fields);*/


        //插入
        /*$TableDataInsertAllRequest = new \Google_Service_Bigquery_TableDataInsertAllRequest();
        $TableDataInsertAllRequestRows = new \Google_Service_Bigquery_TableDataInsertAllRequestRows();
        $data = [
            'udid'=>'uar_1678069919n9xkalah3y3g6xx47p',
            'status'=>'1',
            'request_id'=>'tapplus_admin__64191A06346FD0S0120325776',
        ];
        $TableDataInsertAllRequestRows->setJson($data);
        $id = 'A1D5rTS0eCDdT8Wh';
        $TableDataInsertAllRequestRows->setInsertId($id);
        $rows = array();
        $rows[0] = $TableDataInsertAllRequestRows;
        $TableDataInsertAllRequest->setKind('bigquery#tableDataInsertAllRequest');
        $TableDataInsertAllRequest->setRows($rows);
        $data = $service->tabledata->insertAll($project_id,$datasetId,'test',$TableDataInsertAllRequest);
        dump($data->getInsertErrors());*/
        //列出表数据列表(无条件
        /*$data = $service->tabledata->listTabledata($project_id,$datasetId,'test',[
            //'selectedFields'=>'event_date',
            //'startIndex' => '0',
            //'maxResults'=>'1'
        ]);*/

        $ptable = "{$project_id}.{$datasetId}.test";
        //非服务service化的自定义组件
        $cloud = new ServiceBuilder([
            'projectId' => $project_id,
            'keyFile' =>$configuration
        ]);
        $bigQueryClient = $cloud->bigQuery();


        // (可自定义查询sql
        /*
        $queryJobConfig = $bigQueryClient->query(
            "SELECT * FROM `{$ptable}` where `status` = '2'"
        );
        $queryResults = $bigQueryClient->runQuery($queryJobConfig);

        foreach($queryResults->rows() as $row){
            dump($row);
        }*/

        //job model
//        foreach ($service->jobs->listJobs($project_id) as $item){
//             /* @var $item \Google\Service\Bigquery\JobListJobs */
//        }
//        foreach ($service->models->listModels($project_id) as $item){
//            /* @var $item \Google\Service\Bigquery\Model */
//        }

        //上传的文件数据到bigquery
        /*
        $table = $bigQueryClient->dataset($datasetId)->table('test');
        $loadJobConfig = $table->load(
            fopen('big_query_export.csv', 'r')
        );
        $job = $table->runJob($loadJobConfig);
        $status = $job->isComplete();*/
        //插入
        /*$table = $bigQueryClient->dataset($datasetId)->table('test');
        $data = [
            'udid'=>'777666uar_1678069919n9xkalah3y3g6xx47p',
            'status'=>'1',
            'request_id'=>'tapplus_admin__64191A06346FD0S0120325776',
        ];
        $InsertResponse = $table->insertRow($data,['insertId'=>'A1D5rTS0eCDdT8Wh']);*/



        //$extractJobConfig = $table->extract('gs://my_bucket/target.csv');
        //$bigQueryClient->extract()->sourceTable($table)->destinationUris(['big_query_export.csv']);

        return json_encode($data ?? []);
        //return getEventId(11,uniqid('uios_1645007607snk3x6baw5m0y4i0j'));
        $Shushu = new Shushu(7);
        $request_id = '63FF4CA647D1B1S0164947979';
        $account_id = 'uios_1645007607snk3x6baw5m0y4i0j';
        $event = [
            'finish_time'=>date('Y-m-d H:i:s'),
        ];

        $status = $Shushu->track_update($request_id,'',$event,BasePush::EVENT_SKD_REQUEST,
            $request_id,false);
        //$status = $Shushu->logBusEvent('',$account_id,BasePush::EVENT_DEVICE_PUSH_LOG,$event);
        return compact('status','event','request_id','account_id');

        return json($params);
    }

    public function add_token_infos(Request $request){
        $TokenInfo = new TokenInfo();
        $data = $TokenInfo->first()->toArray();
        $data['ip'] = '127.0.0.1';
        unset($data['id']);
        $count = 50000;
        $datas = [];
        for($i=0;$i<=$count;$i++){
            $prefix = str_repeat('0',strlen($count) - strlen($i));
            $tag_cont = 15 - strlen($prefix) - strlen($i);
            $randomStr = randomStr($tag_cont);
            $index = $prefix.$i.$randomStr;
            $data['udid'] = 'uar_188'.time().$index;
            $data['updated_at'] = '2023-01-01 00:00:00';
            $data['token'] = '12b7eaa38d042beb26221add8b6c9aeb2446cbe69565b62587c'.$index;
            $datas[] = $data;
            if($i % 500==0){
                $TokenInfo->insert($datas);
                $datas = [];
            }
        }



        return json($data);
    }

    public function clientParams(Request $request){
        $json = '{"push_payloads":"[{\"push_data\":{\"notification\":{\"title\":\"1-\u4e2a\u4eba\u90ae\u4ef6\u7b80\u4f53\",\"body\":\"\"},\"custom_data\":{\"color\":\"#cddf15\",\"setSubtitle\":\"1-\u4e2a\u4eba\u90ae\u4ef6\",\"data\":[],\"badge\":0}},\"udid\":\"uar_1675059190nz0pof3ndd3gta7b3z\",\"package_id\":17}]","version":"1.1","sign":"628238ff352a93e8bd145a9f8ad89f94","game_id":"7"}';
        $params = json_decode($json,true);
        foreach ($params as $field =>$param){
            try{
                echo $field.':'.$param.PHP_EOL;
            }catch (\Throwable $exception){
                dump($exception->getMessage());
            }

        }
    }
    public function test_download(Request $request){
        $TokenInfo = new TokenInfo();
        //cate_id`, `channel_id`, `game_id`, `os_id`, `package_id`, `token`, `udid`, `ip`, `updated_a
        $data = [
            'udid'=>'uios_1645007607snk3x6baw5m0y4i0j6',
            'token'=>'test',
            'cate_id' =>7,
            'game_id'=>5,
            'package_id'=>11,
            'ip'=>'127.0.0.1',
            'updated_at'=>date('Y-m-d H:i:s'),
            'channel_id'=>9
        ];
        $data2 = [
            'udid'=>'duios_1645007607snk3x6baw5m0y4i0j',
            'token'=>'dtest',
            'cate_id' =>7,
            'game_id'=>5,
            'package_id'=>11,
            'ip'=>'127.0.0.1',
            'updated_at'=>date('Y-m-d H:i:s'),
            'channel_id'=>9
        ];
        $unique_columns = ['udid'];
        $update_column = ['updated_at','token'];
        /*$status = Db::table($TokenInfo->getTable())->upsert([$data],[],[
            'updated_at',
            'token',
            //'os_id',
            //'channel_id'
        ]);*/
        /*$status = Db::table($TokenInfo->getTable())->insertOrIgnore($data);
        if(!$status){
            $status = Db::table($TokenInfo->getTable())
                ->where(array_intersect_key($data,array_combine($unique_columns, array_fill(0, count($unique_columns), ""))))
                ->update(array_intersect_key($data,array_combine($update_column, array_fill(0, count($update_column), ""))));
        }*/

            $status = Db::table($TokenInfo->getTable())
                ->where(array_intersect_key($data,array_combine($unique_columns, array_fill(0, count($unique_columns), ""))))
                ->update(array_intersect_key($data,array_combine($update_column, array_fill(0, count($update_column), ""))));
            if(!$status) {
                $status = Db::table($TokenInfo->getTable())->insertOrIgnore($data);
            }






        //无原则性
        /*$attributes = array_intersect_key($data,array_combine($unique_columns, array_fill(0, count($unique_columns), "")));
        $status = Db::table($TokenInfo->getTable())->updateOrInsert($attributes,$data);*/
        return $status;
        /*$post = $request->post();
        $get = $request->get();
        $header = $request->header();
        $cookie = $request->cookie();
        $session = $request->session();
        $path= $request->path();*/
        $field = ['udid','token'];
        $whereList = [
            [
                'where',['package_id',11]
            ],
            /*[
                'where',['id',5]
            ],*/
        ];
        $data = [
            'whereList' => $whereList,
            'object' => 'admin_download/test_push/'.uniqid().'test.csv',
            'field' => $field,
        ];
        $status = \app\queue\redis\download\DownToken::publicSend($data);
        //dump($data);
        //$status = intval(Redis::send('queue_download_tokens',$data));

        $return['status'] = $status;
        return json($return);
        return json(compact('post','get','header','cookie','session','path') +$return);
    }

    public function download_progress(Request $request){
        $object = $request->input('object','');
        $tag = Redis::get(\app\queue\redis\download\DownToken::statusKey($object));
        $Oss = new \app\extensions\api\Oss();
        return '剩余次数:'.$tag.'<meta name="referrer" content="no-referrer" /><a target="_blank" href="'.$Oss::DOMAIN.'/'.$object.'">下载</a>';
    }

    public function download_token(Request $request){
        $type = $request->input('type',0);
        $all = $request->post();
        if($type){
            $all = array_merge($all,$request->get());
        }
        $package_id = $all['package_id'] ?? 0;
        $role_name = $all['role_name'] ?? '';
        $server_name = $all['server_name'] ?? '';
        $field = $all['field'] ?: ['udid','token'];
        $name = requestId('_'.implode('_',$field).'_');
        $object = DownToken::$path.$name.'.csv';

        if($type || $package_id){

            $Package = new Package();
            $data = $Package->where('id',$package_id)->first();
            if(empty($data)){
                return '游戏包id：'.$package_id.'错误';
            }
            $whereList = [];

            //游戏包id
            $whereList[] = ['where',['package_id',$package_id]];
            $cate_id = $data->cate_id;
            $raw = [];
            $role_name && $role_name = urlencode($role_name);
            $role_name && $raw[] = "(role_id = '{$role_name}' or role_name like '%{$role_name}%')";
            $server_name && $raw[] = "(server_id = '{$server_name}' or server_name = '{$server_name}')";

            if($raw){
                $build = Db::connection('mysql_data')->table('roles_'.$cate_id)
                    ->whereRaw(implode(' and ',$raw))->orderBy('id','desc');
                $count = $build->count('udid');


                //mysql in限制
                $chunk = 10000;
                $times = $page = ceil($count / $chunk);
                Redis::set(\app\queue\redis\download\DownToken::statusKey($object),$times);//记录次数
                Redis::expire(\app\queue\redis\download\DownToken::statusKey($object),86400);
                for($i=1;$i<=$page;$i++){
                    $nWhereList = $whereList;
                    $udids = $build->offset(($i-1)* $chunk)->limit($chunk)->pluck('udid')->toArray();
                    $nWhereList[] = ['wherein',['udid',$udids]];
                    $qdata = [
                        'whereList' => $nWhereList,
                        'object' => $object,
                        'field' => $field,
                    ];
                    //直接加队列
                    Redis::send(\app\queue\redis\download\DownToken::$redis_queue_key,$qdata);
                }

            }else{
                $qdata = [
                    'whereList' => $whereList,
                    'object' => $object,
                    'field' => $field,
                ];
                $times = \app\queue\redis\download\DownToken::publicSend($qdata);//会自动分页
            }

            $log = '分批下载,次数:'.$times;
            if($times){
                $log.= ',<a href="/download_token/progress?object='.$object.'">查看进度</a>';
            }
            return $log;

            /*$display_name = $data->id.'['.$data->appname.']_token'.date('Ymd').'_'.uniqid();
            $outformat = $display_name.".csv";
            $title = "udid,token"."\r\n";
            $TokenInfo = new TokenInfo();
            $build = $TokenInfo;
            $build = $build->where('package_id',$package_id);
            if($udids){
                $build = $build->wherein('udid',$udids);
            }else{
                if($limit){
                    $build = $build->offset(0)->limit($limit);
                }
            }

            $build = $build->orderBy('updated_at','asc');
            $list = $build->select()->get();

            $data = '';
            foreach ($list as $item) {
                $data .= "{$item['udid']},{$item['token']}"."\r\n";
            }
            $data = $title . $data;
            return response()->withHeaders([
                'Cache-control'=>'private',
                'Pragma'=>'public',
                'Content-type'=>'application/x-csv',
                "Content-Disposition"=>"attachment; filename=$outformat",
            ])->withBody($data);
            //return response()->download(public_path() . '/favicon.ico', $outformat);*/
        }else{
            $ids = array_keys(Package::getPackageConfig());
            $Game = new Game();
            $fields = ['p.game_id','p.id','p.name','p.appname'];
            $packageList = $Game->from($Game->getTable().' as g')->rightJoin('packages as p','p.game_id','g.id')
                ->wherein('p.id',$ids)
                ->select($fields)->get()->toArray();
            return view('index/download_token', ['packageList' => $packageList]);
        }
    }

    public function config(Request $request){
        $update = $request->input('updateGetConfig',0);
        if($update){
            return json_encode(Package::updateGetConfig(null,true));
        }
        $data = Package::getPackageConfig();
        return json_encode($data);
    }
}
